package com.century.sjt.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.century.sjt.R;
import com.century.sjt.activity.Pay.CommodityListActivity;
import com.century.sjt.activity.order.MerchantOrderActivity;
import com.century.sjt.activity.order.MyOrderActivity;
import com.century.sjt.activity.setting.SettingActivity;
import com.century.sjt.activity.wallet.WalletActivity;
import com.century.sjt.entity.Merchant;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 炳基 on 2016/8/12.
 */
public class MyActivity extends BaseActivity {
    private LinearLayout show_me_zhxx, show_me_qb, show_me_sz, show_me_yqm;//show_me_qrr;
    private LinearLayout llMyOrder;
    private ImageView ciHeadimage;
    private TextView tvNickName;
    private String isShop, shopId,isMerchant;
    //private LinearLayout show_me_commodit;
    //private View show_view_commodit;
    //private ImageView img1, img2, img3, img4, img5;
    //private List<ImageView> imgList = new ArrayList<>();
    private LinearLayout left_layout;
    private TextView left_icon, right_icon2, purse_tv, invite_tv, order_tv,center_tv_icon;
    private ImageView goodsImage[] = new ImageView[4];
    private LinearLayout layout_commodity;
    SharedPreferences mainSharedPreferences;
    String image;
    String nickName;
    private RequestQueue mQueue;
    private Merchant aMerchant;
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_myactivity);
        mainSharedPreferences = getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
        isShop = mainSharedPreferences.getString("isShop", "");
        isMerchant = mainSharedPreferences.getString("isMerchant", "");
        image = mainSharedPreferences.getString("image", "");
        nickName = mainSharedPreferences.getString("nickName", "");
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);//软键盘设置
        initView();
        initEvent();
    }

    @Override
    public void onResume() {
        super.onResume();
        }

    @Override
    protected void initView() {
        mQueue = Volley.newRequestQueue(this);
        left_icon = (TextView) findViewById(R.id.left_icon);
        right_icon2 = (TextView) findViewById(R.id.right_icon2);
        purse_tv = (TextView) findViewById(R.id.purse_tv);
        invite_tv = (TextView) findViewById(R.id.invite_tv);
        order_tv = (TextView) findViewById(R.id.order_tv);

        Typeface iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");
        left_icon.setTypeface(iconfont);
        right_icon2.setTypeface(iconfont);
        purse_tv.setTypeface(iconfont);
        invite_tv.setTypeface(iconfont);
        order_tv.setTypeface(iconfont);

        ciHeadimage = (ImageView) findViewById(R.id.profile_image);
        tvNickName = (TextView) findViewById(R.id.tv_nick_name);
        show_me_zhxx = (LinearLayout) findViewById(R.id.me_show_zhxx);
        show_me_qb = (LinearLayout) findViewById(R.id.me_show_qb);
        show_me_sz = (LinearLayout) findViewById(R.id.me_show_sz);
        show_me_yqm = (LinearLayout) findViewById(R.id.me_show_yqm);
       // show_me_qrr= (LinearLayout) findViewById(R.id.rightlayout_icon1);
        llMyOrder = (LinearLayout) findViewById(R.id.ll_my_order);
        left_layout = (LinearLayout) findViewById(R.id.left_layout);
        layout_commodity= (LinearLayout) findViewById(R.id.layout_commodity);

        //  获取头像实例
        if (!"".equals(image)) {
            Glide.with(MyActivity.this).load(Constant.ImageHost_Big + image).into(ciHeadimage);
        }
        if ("1".equals(isShop)) {
            shopId = mainSharedPreferences.getString("shopId", "");
        }
        tvNickName.setText(nickName);
        if (isMerchant.equals("0") & isShop.equals("0")){
            layout_commodity.setVisibility(View.GONE);
        }else{
            goodsImage[0] = (ImageView) findViewById(R.id.iv_goods1);
            goodsImage[1] = (ImageView) findViewById(R.id.iv_goods2);
            goodsImage[2] = (ImageView) findViewById(R.id.iv_goods3);
            goodsImage[3] = (ImageView) findViewById(R.id.iv_goods4);
            layout_commodity.setVisibility(View.VISIBLE);
            shopDetail(shopId);
        }

    }

    @Override
    protected void initEvent() {
        show_me_zhxx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MyActivity.this, MydataActivity.class);
                startActivity(intent);
            }
        });

        //我的订单
        llMyOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断是商家、分店、还是用户
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String isMerchant = mainSharedPreferences.getString("isMerchant", "");
                String isShop = mainSharedPreferences.getString("isShop", "");

                if(isMerchant.equals("0")&isShop.equals("0")){
                    //用户
                    startActivity(MyActivity.this, MyOrderActivity.class);
                }else{
                    //商家、分店
                   startActivity(MyActivity.this, MerchantOrderActivity.class);
                }

            }
        });

        show_me_qb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MyActivity.this, WalletActivity.class);
                startActivity(intent);
            }
        });

        show_me_sz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MyActivity.this, SettingActivity.class);
                startActivity(intent);
            }
        });

        show_me_yqm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MyActivity.this, MyInviteNumberActivity.class);
                startActivity(intent);

            }
        });
//        show_me_qrr.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivity(MyActivity.this,QRRecordCodeScanActivity.class);
//            }
//        });
        left_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //我的商品
        layout_commodity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MyActivity.this, CommodityListActivity.class);
                intent.putExtra("shopId",aMerchant.getShopId());
                intent.putExtra("shopName",aMerchant.getShopName());
                startActivity(intent);
            }
        });


    }

    @Override
    protected void initData() {

    }

    /**
     * 获取商品图片四张
     *
     * @param newGoods
     */
    private void setNewGoodsImage(String newGoods) {
        String[] imageUrls = newGoods.split("\\|");
        for (int i = 0; i < imageUrls.length; i++) {
            String imageUrl = newGoods.split("\\|")[i];
            if(!"".equals(imageUrl)) {//如果不为空字符
                if(i<3) {//小于四张图片
                    goodsImage[i].setVisibility(View.VISIBLE);
//                    Log.e("img",imageUrl);
                    Glide.with(this).load(imageUrl).into(goodsImage[i]);
                }
            }
        }
    }

    /**
     * 获取商店详情
     * @param shopId
     */
    private void shopDetail(final String shopId) {
        TipUtil.openProgressDialog(com.century.sjt.util.Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), MyActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, com.century.sjt.util.Constant.ShopDetail, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口返回成功", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        JSONObject aData = res.getJSONObject("data");
                        Merchant merchant = new Merchant();
                        merchant.setShopId(aData.getString("shopId"));
                        merchant.setShopName(aData.getString("shopName"));
//                            Log.e("name",aData.getString("shopName"));
                        merchant.setLogo(aData.getString("logo"));
                        merchant.setDiscount(aData.getString("discount"));
                        merchant.setAddress(aData.getString("address"));
                        merchant.setTelephone(aData.getString("telephone"));
                        merchant.setTelephoneOne(aData.getString("telephoneOne"));
                        merchant.setMobile(aData.getString("mobile"));
                        merchant.setDesc(aData.getString("desc"));
                        merchant.setCity(aData.getString("city"));
                        merchant.setImage(aData.getString("image"));
                        merchant.setUserId(aData.getString("userId"));
                        merchant.setLastTopic(aData.getString("lastTopic"));
                        merchant.setNewGoods(aData.getString("newGoods"));
                        merchant.setDetailsUrl(aData.getString("detailsUrl"));
                        merchant.setNationalFlag(aData.getString("nationalFlag"));
                        merchant.setCurrencyCode(aData.getString("currencyCode"));
                        merchant.setCurrency(aData.getString("currency"));
                        merchant.setExRate(aData.getString("exRate"));
                        merchant.setDiscountDeduct(aData.getString("discountDeduct"));
                        merchant.setVipDiscountDeduct(aData.getString("vipDiscountDeduct"));
                        aMerchant = merchant;
                        setNewGoodsImage(aMerchant.getNewGoods());//获取商品图片四张
                    } else {//失败
                        TipUtil.showToast(message, MyActivity.this, 1);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service),MyActivity.this, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), MyActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
//                SharedPreferences mainSharedPreferences =getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
//                String userId = mainSharedPreferences.getString("userId", "");
//                map.put("loginId", userId);
                map.put("shopId",shopId);
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences =getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }



}
